package com.hcrazy.manchester.app.services;

import com.hcrazy.manchester.app.jdbc.AdminDAO;
import com.hcrazy.manchester.app.pojo.Admin;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.utils.Constant;
import com.hcrazy.manchester.app.utils.MD5Util;

public class AdminService {

	private AdminDAO adminDAO;
	
	public AdminDAO getAdminDAO() {
		return adminDAO;
	}

	public void setAdminDAO(AdminDAO adminDAO) {
		this.adminDAO = adminDAO;
	}

	public Admin getAdminByUserNameOrEmail(Admin admin) throws Exception{
		return adminDAO.getAdminByUsernameOrEmail(admin);
	}
	
	public int login(Admin admin) throws Exception{
		if(null == admin)
			return 0;
		String username = admin.getAdminName();
		String password = admin.getAdminPassword();
		if(null == username || "".equals(username))
			return 0;
		if(null == password || "".equals(password))
			return 0;
		
		Admin u = null;
		try {
			admin.setAdminEmail(username);
			u = adminDAO.getAdminByUsernameOrEmail(admin);
		} catch (Exception e1) {
			if(e1.getMessage().contains("expected 1, actual 0")){
				return Constant.LOGIN_RESULT_USERNAME_FAILED;
			}
		}
		if(null == u) return 0;
		
		String oldPass = u.getAdminPassword();
		try {
			String newPass = MD5Util.fromStringToMD5(password);
			if(!newPass.equals(oldPass)){
				return Constant.LOGIN_RESULT_PASSWORD_FAILED;
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	
		return Constant.LOGIN_RESULT_SUCCESS;
	}
	
	public Admin getAdmin(int adminId) throws Exception{
		return adminDAO.getAdmin(adminId);
	}
	
	public ErrorMsg changePassword(Admin admin,String oldPass,String newPass) throws Exception{
		if(null == oldPass || null == newPass || "".equals(oldPass) || "".equals(newPass)){
			return new ErrorMsg(Constant.FAILED,"失败！");
		}
		if(null == admin || null == admin.getAdminPassword()){
			return new ErrorMsg(Constant.FAILED,"失败！");
		}
		String pass = MD5Util.fromStringToMD5(oldPass);
		if(!admin.getAdminPassword().equals(pass)){
			return new ErrorMsg(Constant.ERROR_CODE_ERROR_PASSWORD,"密码输入错误！");
		}
		
		newPass = MD5Util.fromStringToMD5(newPass);
		admin.setAdminPassword(newPass);
		adminDAO.updateAdmin(admin);
		
		return new ErrorMsg(Constant.SUCCESS);
	}
	
	public ErrorMsg validate(Admin admin) throws Exception{
		if(null == admin)
			return new ErrorMsg(Constant.ERROR_CODE_NO_OBJECT);
		
		if(null == admin.getAdminName() || "".equals(admin.getAdminName()))
			return new ErrorMsg(Constant.ERROR_CODE_EMPTY_NAME);
		
		if(null == admin.getAdminPassword() || "".equals(admin.getAdminPassword()))
			return new ErrorMsg(Constant.ERROR_CODE_EMPTY_PASSWORD);
		
		return null;
	}
	
}
